#include "common.hpp"

int main()
{
    // 由服务端负责申请 创建 + 释放 共享内存空间

    key_t key = getKey();
    printf("key : 0x%x\n", key);

    int shmid = createShm(key);
    printf("shmid : %d\n", shmid);

    char *mem = (char*)shmAttach(shmid);   // 有点像malloc的意思
    printf("server attach success!, address start : %p\n", mem);

    // 通信
    while(true)
    {
        printf("client -> server say# : %s\n", mem);
        sleep(1);

        struct shmid_ds ds;
        shmctl(shmid, IPC_STAT, &ds);
        // printf("获取属性 -> size : %d, pid : %d, myself_pid : %d, key : 0x%x\n", ds.shm_segsz, ds.shm_cpid, getpid(), ds.shm_perm.__key);
        if(ds.shm_nattch == 1)
        {
            int count = 10;

            while(--count != 0)
            {
                sleep(1);
                shmctl(shmid, IPC_STAT, &ds);
                if(ds.shm_nattch > 1)
                    break;
            }

            if(count == 0)
            {
                printf("一小会儿过去了, 当前没有客户端向我发数据, 我也先退了!告辞!\n");
                break;
            }
        }
    }

    shmDetach(mem);
    printf("server detach success!\n");

    delShm(shmid);
    printf("server delete the shm success!\n");

    return 0;
}